rest接口返回输出流
Introduction
项目需要将rest接口风格查出来的数据导出到xls中。所以有了这篇记录。
其实啦:这个记录,是看了别人的解决方案后,推想出他的解决方案的思路。不知道对不对。先记下再说哈。
需求和解决设想
需求:REST风格的接口也可以进行xls文件导出;
想法:接口根据参数进行查库操作,将结果写入到输出流中。
第一步
查找返回类型中能否返回类似outPutStream的类或接口
寻找[java文档](https://docs.oracle.com/javaee/6/api/
- overview-summary.html)中rs有关的包。
javax.ws.rs High-level interfaces and annotations used to create RESTful service resources. - javax.ws.rs.core Low-level interfaces and annotations used to create RESTful service resources.
- javax.ws.rs.ext APIs that provide extensions to the types supported by the JAX-RS API.
在这些类包中找有关输出流的接口,或者找有关输出流的类。
第二步
javax.ws.rs.core中有StreamingOutput接口;
该接口功能:当接口需要以流的形式返回值的时候,可以用此接口。
那么使接口返回的response实现StreamingOutput接口。并在实现的方法中将xls表格写入输出流。代码如下:1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17public class ExcelStreamingResponse extends ServiceResponse implements StreamingOutput{
private HSSFWorkbook wb;
public ExcelStreamingResponse() {
}
public ExcelStreamingResponse(HSSFWorkbook wb) {
this.wb= wb;
}
public void write(OutputStream output) throws IOException,
WebApplicationException {
if (wb!= null) {
wb.write(output);
}
}
为了使http返回的文件类型为xls,查找http content—type为application/vnd.ms-excel application/x-xls(后者没有试验)
接口设计
那么接口的大概代码设计为:1
2
3
4
5
("/export/xls")
("application/vnd.ms-excel")
//@Context 是为了向方法参数中注入信息,这里是为了绑定返回response的信息
public ExcelStreamingResponse exportXls(@QueryParam("") HttpServletRequest request, @Context HttpServletResponse response) throws Exception;
上述接口实现大致为:1
2
3
4
5
6
7
8
9
10
11
12
13public ExcelStreamingResponse exportXls(
HttpServletRequest request, HttpServletResponse response) throws Exception {
// 查库操作
。。。
// 拼装excel
HSSFWorkbook workbook = new HSSFWorkbook();
。。。
// 设置返回的文件名称
response.setHeader("Content-Disposition", "attachment; filename=我就是一个xls");
return new ExcelStreamingResponse(workbook);
}
现在就可以进行访问下载啦
